{% extends "base.html" %}
{% load staticfiles %}

{% block title %}
    {% if t == 'b' %}
        回测管理
    {% else %}
        模拟管理
    {% endif %}
{% endblock %}

{% block styles %}

{% endblock %}

{% block content %}

    <section class="content-header">
        <h1>
            {% if t == 'b' %}
                回测管理
            {% else %}
                模拟管理
            {% endif %}
            <small>{{ allHtml.title }}</small>
        </h1>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-xs-12">
                <div class="nav-tabs-custom">
                    <div class="tab-content ">
                        <div class="tab-pane active mailbox-messages" id="fa-icons">
                            <div class=" mailbox-messages">
                                <table class="table table-bordered table-striped table-hover"
                                       id="StrategyBackTestTable">

                                </table>
                                <input type="text" style="display: none" id="stgid" value="{{ stgid }}">
                            </div>
                        </div>
                        <div class="tab-pane" id="glyphicons">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>


    <!-- UserModal content -->
    <div class="modal fade" id="modal_backtest_detail">
        <div class="modal-dialog" style="width: 1200px;height:600px">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" style="padding: 30px;height:auto;">
                    <div align="center" class="form-inline">
                        <label class="lab get_head" id="L1">收益概览</label>
                        <label class="lab trade_head" id="L2">交易明细</label>
                        <label class="lab" id="L3" style="display: none">持仓详情</label>
                    </div>
                    {# 实盘指标#}
                    <div class="row L1">
                        <div class="col-md-12">
                            <div class="box box-primary">
                                <div class="box-header with-border">
                                    <h3 class="box-title">收益概览</h3>
                                    <div>
                                        <p></p>
                                        <table class="table">
                                            <tbody>
                                            <tr class="back-detail">
                                                <th data-align="center">起始日期</th>
                                                <th data-align="center">结束日期</th>
                                                <th data-align="center">回测收益</th>
                                                <th data-align="center">回测年化收益</th>
                                                <th data-align="center">夏普率</th>
                                                <th data-align="center">索提诺比率</th>
                                                <th data-align="center">calmar比率</th>
                                                <th data-align="center">年化波动率</th>
                                                <th data-align="center">最大回撤</th>
                                            </tr>
                                            <tr>
                                                <td data-align="center" id="start_date"></td>
                                                <td data-align="center" id="end_date"></td>
                                                <th data-align="center" id="total_return"></th>
                                                <th data-align="center" id="annual_return"></th>
                                                <td data-align="center" id="sharpe_ratio"></td>
                                                <td data-align="center" id="sortino_ratio"></td>
                                                <td data-align="center" id="calmar_ratio"></td>
                                                <td data-align="center" id="annual_volatility"></td>
                                                <td data-align="center" id="max_draw_down"></td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="box-header with-border">
                                    <h3 class="box-title">净值曲线</h3>
                                </div>
                                <div class="box-body " style="padding: 10px; height:350px;">
                                    <div id="cumulativereturns" style="height: 230px; width: 100%;">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {# K线#}
                    <div class="row L2" style="display: none">
                        <div class="col-md-12">
                            <div class="box box-primary">
                                <div class="box-header with-border">
                                    <h3 class="box-title">买卖点</h3>
                                </div>
                                <div id="symbols_button" style="padding-left:20px">

                                </div>
                                <div class="box-body " style="height:350px">
                                    <div id="loading-center-absolute" style="display:none">
                                        <div class="object" id="object_one"></div>
                                        <div class="object" id="object_two"></div>
                                        <div class="object" id="object_three"></div>
                                    </div>
                                    <div id="candlestik" style="height: 280px;width: 100%">

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {#成交信息#}
                    <div class="row L2">
                        <div class="col-md-12">
                            <div class="box box-primary">
                                <div class="box-header with-border">
                                    <h3 class="box-title">成交信息</h3>
                                </div>
                                <div style="width:100%; height:650px">
                                    <table class="table table-bordered table-striped table-hover" id="trade_table"
                                           style="width: 100%; height:auto">
                                    </table>

                                </div>
                            </div>
                            <!-- /. box -->
                        </div>
                    </div>
                    <div class="L3" style="height:800px">
                        <h4>持仓详情</h4>
                        <hr>
                        <div style="width:100%; height:650px">
                            <table style="width:100%; height:500px" id="position_info"
                                   class="table table-bordered table-striped table-hover">
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block scripts %}
    <style>
        #loading-center-absolute {
            position: relative;
            z-index: 1;
            left: 50%;
            top: 50%;
            width: 150px;
            margin-top: -75px;
            margin-left: -75px;
        }

        .object {
            width: 20px;
            height: 20px;
            background-color: #ff4400;
            float: left;
            margin-right: 20px;
            margin-top: 65px;
            -moz-border-radius: 50% 50% 50% 50%;
            -webkit-border-radius: 50% 50% 50% 50%;
            border-radius: 50% 50% 50% 50%;
        }

        #object_one {
            -webkit-animation: object_one 1.5s infinite;
            animation: object_one 1.5s infinite;
        }

        #object_two {
            -webkit-animation: object_two 1.5s infinite;
            animation: object_two 1.5s infinite;
            -webkit-animation-delay: 0.25s;
            animation-delay: 0.25s;
        }

        #object_three {
            -webkit-animation: object_three 1.5s infinite;
            animation: object_three 1.5s infinite;
            -webkit-animation-delay: 0.5s;
            animation-delay: 0.5s;
        }

        @-webkit-keyframes object_one {
            75% {
                -webkit-transform: scale(0);
            }
        }

        @keyframes object_one {
            75% {
                transform: scale(0);
                -webkit-transform: scale(0);
            }
        }

        @-webkit-keyframes object_two {
            75% {
                -webkit-transform: scale(0);
            }
        }

        @keyframes object_two {
            75% {
                transform: scale(0);
                -webkit-transform: scale(0);
            }
        }

        @-webkit-keyframes object_three {
            75% {
                -webkit-transform: scale(0);
            }
        }

        @keyframes object_three {
            75% {
                transform: scale(0);
                -webkit-transform: scale(0);
            }
        }

        .lab {
            font-size: 15px;
            width: 150px;
            border-width: 1px;
            border-style: solid;
            border-color: #000;
        }

        .get_head {
            float: left;
            margin-left: 40%;
        }

        .trade_head {
            float: left;
        }

        .table-striped > tbody > tr:nth-of-type(odd) {
            background-color: #00000026;
        }

        .table-striped > tbody > tr:nth-of-type(even) {
            background-color: #00000026;
        }

        .table-hover > tbody > tr:hover {
            background-color: #00000026;
            cursor: pointer;
        }
    </style>
    <script type="text/javascript">
        (function ($) {
            $.getUrlParam = function (name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }
        })(jQuery);
        var tableName = "StrategyBackTestTable";

        function gets() {
            let stgid = $("#stgid").val();
            let msid = $('#sid').val();
            $('#' + tableName).dataTable().fnDestroy();
            var userdataTable = initdataTable(tableName, lengthMenu, urlParam, columnsParam, stgid, msid);
        }

        var lengthMenu = '<div class="btn-group">' +
            '<button type="button" class="btn btn-de">' + "<a href='{% url 'Strategy:strategy_list' %}'>返回策略列表</a></button>" +
            '</div>' + "&nbsp;&nbsp;&nbsp;&nbsp;"
            + '<span>策略名称 </span><input class="stgname" type="text" id="sid"><button class="btn-suc" onclick="gets()">查询</button>';
        var strategyId = $.getUrlParam('strategyId');
        var urlParam = "{% url 'Strategy:backtest' %}";
        var columnsParam = [
            {#{title: "id", data: "id", sClass: "hidden"},#}
            {title: "策略id", data: "StrategyId", sClass: "hidden"},
            {title: "策略名称", data: "StrategyName"},
            {title: "回测ID", data: "BacktestID"},
            {title: "执行时间", data: "BackTestTime"},
            {#{title: "回测频率", data: "Frequency"},#}
            {title: "开始时间", data: "StartTime"},
            {title: "结束时间", data: "EndTime"},
            {title: "状态", data: "RunStatus"},
            {
                title: "操作", data: null, sClass: 'operation',
                "render": function (data, type, full, meta) {
                    var userModify = "<lable class='lab' onclick='mods()'><button type='button' class='btn btn-detail btn-xs btn-flat btn_operation'  data-toggle='modal' data-target='#modal_backtest_detail'> <i class='fa fa-pencil'></i>查看详情</button ></label> ";
                    return userModify;
                }
            }
        ];
        var userdataTable = initdataTable(tableName, lengthMenu, urlParam, columnsParam, strategyId, "");
        {#单击选中，操作栏无法选中#}
        <!--        $('#StrategyBackTestTable tbody').on("click", 'tr td', function () {-->
        <!--            if ($(this)[0].className.trim() != 'operation') {-->
        <!--                $(this).parents("tr").toggleClass('selected');-->
        <!--                var isSelect = $(this).parents("tr").hasClass('selected');-->
        <!--                if (isSelect) {-->
        <!--                    $(this).parents("tr").find("input").iCheck("check");-->
        <!--                } else {-->
        <!--                    $(this).parents("tr").find("input").iCheck("uncheck");-->
        <!--                }-->
        <!--            }-->
        <!--        });-->
        {#操作-修改、激活、禁用#}
        var oTable = null;
        //成交信息展示
        $('#StrategyBackTestTable tbody').on("click", '.btn_operation', function () {
            var tr = $(this).parents("tr");
            var data = userdataTable.fnGetData($(tr));
            position_sid = data.StrategyId
            position_bid = data.BacktestID
            gid = position_sid + "__" + position_bid;
            var id = gid;
            var tableName_trade = "trade_table";
            var lengthMenu_trade = '';
            var strategyId_trade = id;
            var urlParam_trade = "{% url 'Strategy:detail_trade_list_table' %}";
            {#持仓详情的数据展示#}

            function InitBootstrapTable(my_url, my_table_id, my_columns, my_filename) {
                $('#' + my_table_id).bootstrapTable('destroy').bootstrapTable({
                    url: my_url,
                    method: 'get',
                    columns: my_columns,
                    {#toolbar: '#toolbar',       #}
                    striped: true,
                    cache: false,
                    pagination: true,
                    sortable: true,
                    sortOrder: "asc",
                    queryParams: function (pageRequest) {
                        if ($('.L2').attr('hidden')) {
                            sea = $('.L3 .search .form-control').val();
                        } else {
                            sea = $('.L2 .search .form-control').val();
                        }
                        var tmp = {
                            offset: pageRequest.offset,
                            limit: this.pageSize,
                            sid: gid,
                            search: sea,
                        };
                        return tmp;
                    },
                    sidePagination: "server",
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    {#    search: true,        #}
                    {#            strictSearch: true,#}
                    {#            showColumns: true,      #}
                    {#            showRefresh: true,      #}
                    minimumCountColumns: 2,
                    clickToSelect: true,
                    uniqueId: "_id",
                    {#    showToggle: true,    #}
                    cardView: false,
                    detailView: false,
                    {#    showExport: true,#}
                    buttonsAlign: "right",
                    exportDataType: "all",
                    exportTypes: ['excel'],
                    Icons: 'glyphicon-export',
                    exportOptions: {
                        fileName: my_filename,
                        worksheetName: 'Sheet1',
                        tableName: my_filename,
                    },
                })
            };
            my_columns = [
                {
                    field: 'accountID',
                    title: '资金账号'
                }, {
                    field: 'symbol',
                    title: '合约'
                }, {
                    field: 'exch',
                    title: '交易所'
                }, {
                    field: 'date',
                    title: '日期&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
                }, {
                    field: 'close',
                    title: '收盘价'
                }, {
                    field: 'bidQty',
                    title: '多头持仓'
                }, {
                    field: 'bidPx',
                    title: '多头开仓均价',
                }, {
                    field: 'bidMargin',
                    title: '多头保证金',
                }, {
                    field: 'bidPNL',
                    title: '多头累计盈亏',
                }, {
                    field: 'askQty',
                    title: '空头持仓',
                }, {
                    field: 'askPx',
                    title: '空头开仓均价',
                }, {
                    field: 'askMargin',
                    title: '空头保证金',
                }, {
                    field: 'askPNL',
                    title: '空头累计盈亏',
                },
            ];
            InitBootstrapTable("{% url 'Strategy:position' %}", "position_info", my_columns, "position" + gid);
            {# 成交导出 #}
            trade_col = [
                {
                    field: 'Symbol',
                    title: '合约'
                }, {
                    field: 'TradeTime',
                    title: '成交时间'
                }, {
                    field: 'TradeYTM',
                    title: '成交价格(%)',
                }, {
                    field: "TradePx",
                    title: "成交净价"
                },{
                    field: 'Qty',
                    title: '数量',
                }, {
                    field: 'Direction',
                    title: '买卖',
                }
            ];
            InitBootstrapTable(urlParam_trade, tableName_trade, trade_col, "trade" + gid);

            {#   回测指标   #}
            $.get("{% url 'Strategy:detail_incomeStatistics'%}", {'backtestId': id}, function (result) {
                if (result != null) {
                    $("#annual_volatility").html(result.annual_volatility);
                    $("#sharpe_ratio").html(result.sharpe_ratio);
                    $("#calmar_ratio").html(result.calmar_ratio);
                    $("#omega_ratio").html(result.omega_ratio);
                    $("#sortino_ratio").html(result.sortino_ratio);
                    $("#total_return").html(result.total_return + "%");
                    if (result.total_return > 0) {
                        $("#total_return").css("color", "red");
                    } else {
                        $("#total_return").css("color", "green");
                    }
                    $("#annual_return").html(result.annual_return + "%");
                    if (result.annual_return > 0) {
                        $("#annual_return").css("color", "red");
                    } else {
                        $("#annual_return").css("color", "green");
                    }
                    $("#max_draw_down").html(result.max_draw_down + "%");
                    if (result.max_draw_down > 0) {
                        $("#max_draw_down").css("color", "red");
                    } else {
                        $("#max_draw_down").css("color", "green");
                    }
                    $("#start_date").html(result.start_date);
                    $("#end_date").html(result.end_date);
                } else {
                    $("#annual_return").html('-');
                    $("#annual_volatility").html('-');
                    $("#sharpe_ratio").html('-');
                    $("#calmar_ratio").html('-');
                    $("#stability_of_timeseries").html('-');
                    $("#max_draw_down").html('-');
                    $("#omega_ratio").html('-');
                    $("#sortino_ratio").html('-');
                    $("#annual_return").html('-');
                    $("#start_date").html('-');
                    $("#end_date").html('-');
                }

            });
            cget("", id);
            $.get("{% url 'Strategy:symbol_button' %}", {'gid': gid}, function (result) {
                console.log(result);
                $('.ht').remove();
                for (var i = 0; i < result.length; i++) {
                    var ht = "<button style='margin-left: 5px' class='ht btn-success' onclick=\"cget(" + "\'" + result[i] + "\'," + "\'" + id + "\'" + ")\"" + ">" + result[i] + "</button>";
                    $('#symbols_button').prepend($(ht));
                }
                ;
            });
            $.get("{% url 'Strategy:detail_cumulativereturns'%}", {'backtestId': id}, function (result) {
                console.log('id', id)
                console.log("result", result)
                var myChart = echarts.init(document.getElementById('cumulativereturns'));
                var option = {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function (obj) {
                            return obj[0].seriesName + ":" + obj[0].value + '<br>';
                        }
                    },
                    grid: {
                        left: '5%',   // 与容器左侧的距离
                        right: '5%', // 与容器右侧的距离
                        top: '5%',   // 与容器顶部的距离
                        bottom: '22%', // 与容器底部的距离
                    },
                    dataZoom: [
                        {
                            show: true,
                            realtime: true,
                            start: 0,
                            end: 100
                        },
                        {
                            type: 'inside',
                            realtime: true,
                            start: 0,
                            end: 100
                        }
                    ],
                    xAxis: {
                        type: 'category',
                        data: null,
                        scale: true
                    },
                    yAxis: {
                        type: 'value',
                        scale: true
                    },
                    series: [{
                        name: '净值',
                        data: null,
                        type: 'line',
                    },
                    ]
                };
                if (result != null) {
                    option.series[0].data = result.retData;
                    option.xAxis.data = result.retDate;
                    myChart.setOption(option);
                }
            })
        })

        function mods() {
            $('#L1').css('background-color', '#000');
            $('#L1').css('color', '#fff');
            $('#L2').css('background-color', '#fff');
            $('#L2').css('color', '#000');
            $('#L3').css('background-color', '#fff');
            $('#L3').css('color', '#000');
            $('.L2').css('opacity', '0');
            $('.L3').css('opacity', '0');
            $('.L1').removeAttr('hidden');
            $('.modal-body').css('height', 'auto');
        }

        $('#L1').bind('click', function () {
            $('.l3').css('opacity', '1');
            $('.L2').css('opacity', '1');
            $('.L1').removeAttr('hidden');
            $('.L2').attr('hidden', 'hidden');
            $('.L3').attr('hidden', 'hidden');
            $('#L2').css('background-color', '#fff');
            $('#L2').css('color', '#000');
            $('#L3').css('background-color', '#fff');
            $('#L3').css('color', '#000');
            $('#L1').css('background-color', '#000');
            $('#L1').css('color', '#fff');
            $('.modal-body').css('height', 'auto');
        });
        $('#L2').bind('click', function () {
            $('.l3').css('opacity', '1');
            $('.L1').css('opacity', '1');
            $('.L2').css('opacity', '1');
            $('.L2').removeAttr('hidden');
            $('.L1').attr('hidden', 'hidden');
            $('.L3').attr('hidden', 'hidden');
            $('#L1').css('background-color', '#fff');
            $('#L1').css('color', '#000');
            $('#L3').css('background-color', '#fff');
            $('#L3').css('color', '#000');
            $('#L2').css('background-color', '#000');
            $('#L2').css('color', '#fff');
            $('.modal-body').css('height', 'auto');
            $('.form-control').attr('placeholder', '合约ID查询')
        });
        $('#L3').bind('click', function () {
            $('.l1').css('opacity', '1');
            $('.L2').css('opacity', '1');
            $('.L3').css('opacity', '1');
            $('.L3').removeAttr('hidden');
            $('.L2').attr('hidden', 'hidden');
            $('.L1').attr('hidden', 'hidden');
            $('#L2').css('background-color', '#fff');
            $('#L2').css('color', '#000');
            $('#L1').css('background-color', '#fff');
            $('#L1').css('color', '#000');
            $('#L3').css('background-color', '#000');
            $('#L3').css('color', '#fff');
            $('.modal-body').css('height', 'auto');
            $('.form-control').attr('placeholder', '合约ID查询')
        });
        $('.page-list').css('display', 'none');
        $('.pagination-info').css('display', 'none');


    </script>
    <style>
        .pagination-info {
            display: none
        }

        .page-list {
            display: none
        }

    </style>
    <script>
    </script>
{% endblock %}

